import { useState } from 'react';
import { message, Typography } from 'antd';
import DatePickerModal from './PeriodPickerModal';
import { useDeepCompareEffect } from 'ahooks';
import { PERIOD_DATA } from '@/constants/global.const';
import type { FC } from 'react';

import styles from './index.less';

const { Text } = Typography;

/**
 * 日期选择组件
 * - left: 左侧偏移距离，以em为单位
 */
type TProps = {
  onChange?: TAnyFunction;
  value?: any;
  left?: number;
};

const CommonPeriodPicker: FC<TProps> = (props) => {
  const { onChange, value, left = 6 } = props;
  const [visible, setVisible] = useState<boolean>(false);
  const [data, setData] = useState<TPeriodItem[]>([]);

  const handleSubmit = (val: TPeriodItem[]) => {
    if (!(val && val.length)) {
      message.warn('至少选择一个选项');
    } else {
      onChange && onChange(val.map((o) => o.value));
      setData(val);
      setVisible(false);
    }
  };

  useDeepCompareEffect(() => {
    if (value) {
      const selectedData = PERIOD_DATA.filter((o) => value.includes(o.value));
      setData(selectedData);
    }
  }, [value]);

  const renderText = () => (
    <div className={styles.showWrap}>
      <div className={styles.showContent}>
        <Text>
          <Text strong className="mr-16">
            按餐段
          </Text>
        </Text>
        {data.map((obj) => obj.name).join('、')}
      </div>
      <div className={styles.showBtn} onClick={() => setVisible(true)}>
        编辑
      </div>
    </div>
  );

  return (
    <div className={styles.pickerShowContainer} style={{ paddingLeft: `${left}em` }}>
      <div className={styles.pickerShowBox}>
        {data.length > 0 ? (
          renderText()
        ) : (
          <span
            className={styles.choseBtn}
            onClick={() => {
              setVisible(true);
            }}
          >
            点击选择
          </span>
        )}
      </div>

      {visible && (
        <DatePickerModal
          visible={visible}
          data={data}
          onCancel={() => setVisible(false)}
          onSubmit={handleSubmit}
        />
      )}
    </div>
  );
};

export default CommonPeriodPicker;
